<?php
namespace app\modules\common\components\innercalls\apiconsts;

use app\modules\common\components\Api;
use app\modules\common\components\Common;
use app\modules\common\components\Eureka;
use app\modules\common\components\YiiLog;
use Exception;
use GuzzleHttp\Client;
use Yii;

abstract class AbstractApiConst
{
    public $serverName;

    final public function getServerUrl():string
    {
        try {
            $client = Eureka::getInstance()->getEurekaClient();
            $object = $client->fetchInstance($this->serverName);
            if (!empty($object)) {
                $jsonStr = json_encode($object);
                Yii::info('jsonStr:'.$jsonStr, 'myinfo');

                $jsonArr = json_decode($jsonStr, true);
                if (isset($jsonArr['ipAddr']) && isset($jsonArr['port']) && isset($jsonArr['port']['$'])) {
                    $ipAddress = $jsonArr['ipAddr'];
                    $port = $jsonArr['port']['$'];
                    return "http://".$ipAddress.":".$port;
                } else {
                    throw new Exception("信息有误", Api::CODE_ERROR);
                }
            } else {
                throw new Exception("信息不存在", Api::CODE_ERROR);
            }
        } catch (Exception $exception) {
            throw new Exception($exception->getMessage(), $exception->getCode());
        }
    }

    final public function innerJsonApiCall(array $param = [], string $api = "", array $headers = [], int $timeOut = 10):array
    {
        try {
            $serverUrl = $this->getServerUrl();
            return $this->httpJsonPostWithHeader($serverUrl.$api, $param, $headers, $timeOut);
        } catch (Exception $exception) {
               return Common::codeReturn([], $exception->getCode(), $exception->getMessage());
        }
    }

    final private function httpJsonPostWithHeader($url = "", $data = [], $headers = [], $timeOut = 10)
    {
        try {
            $config = [
                'timeout' => $timeOut
            ];
            $client = new Client($config);

            $option = [
                'json' => $data,
                'headers' => $headers
            ];

            $postResult = $client->post($url, $option);

            $httpCode = $postResult->getStatusCode();
            $content = $postResult->getBody()->getContents();
            if ($httpCode !== 200) {
                throw new Exception('http错误 '.$httpCode." ".$content);
            }

            if (empty($content)) {
                throw new Exception('响应体内容为空');
            }

            $data = json_decode($content, true);
            if (!isset($data['code'])) {
                throw new Exception($content);
            }
            return $data;
        } catch (Exception $exception) {
            YiiLog::info("接口{$url} 请求失败 ".$exception->getMessage());
            
            return Common::codeReturn([], Api::CODE_ERROR, "接口请求失败 ".$exception->getMessage());
        }
    }
}
